/*
This software is distributed under the Simplified BSD License:

Copyright (c) 2008, Chris Venter <chris.venter@gmail.com>
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, 
are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, 
    	this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, 
    	this list of conditions and the following disclaimer in the documentation 
    	and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT 
SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR 
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH 
DAMAGE.
*/
#ifndef GENERIK_SQLITE_H
#define GENERIK_SQLITE_H

/** \file sqlite.h
This file implements the generik::database interface using sqlite as the
database implementation.
*/

#include <sqlite3.h>

#include <iostream>
#include <set>
//#include <dlfcn.h>

#include "../database.h"
#include "../osutils.h"
#include "../threads.h"

#include "../tracing.h"

namespace generik
{
	
	struct sqlite
	: database
	{
		generik::rec_mutex mutex;
		generik::condition condition;
		
		//generik::rec_mutex _notification_mutex;
		std::set<std::string> _notifications;
		
		sqlite3* _dbh;
		bool opened;
		
		sqlite(sqlite3* dbh_in)
		: _dbh(dbh_in)
		, opened(false)
		, mutex("sqlite")
		{
			GENERIK_TRACER;
		}
		
		sqlite(const std::string& filename)
		: opened(false)
		, mutex("sqlite")
		{
			GENERIK_TRACER;
			open(filename);
		}
		
		sqlite()
		: _dbh(0)
		, opened(false)
		, mutex("sqlite")
		{
			GENERIK_TRACER;
		}
		
		~sqlite()
		{
			GENERIK_TRACER;
			if (opened) close();
		}
		
		operator sqlite3*()
		{
			return _dbh;
		}
		
		void open(const std::string& filename)
		{
			GENERIK_TRACER;
			int check = sqlite3_open(filename.c_str(), &_dbh);
			if (check != SQLITE_OK)
			{
				GENERIK_ERROR("sqlite3_open error for ["<<filename<<"]: "<<sqlite3_errmsg(_dbh));
				//exit(-1);
			}
			else
			{
				GENERIK_TRACE("connection succeeded");
				//sqlite3_update_hook(_dbh, notify_callback, (void*)this);
				sqlite3_update_hook(_dbh, update_hook, (void*)this);
				sqlite3_commit_hook(_dbh, commit_hook, (void*)this);
				sqlite3_rollback_hook(_dbh, rollback_hook, (void*)this);
				opened = true;
			}
		}

		void close()
		{
			GENERIK_TRACER;
			if (_dbh)
			{
				// mutex
				mutex.lock();
				sqlite3_close(_dbh);
				_dbh = 0;
				opened = false;
				mutex.unlock();
			}
			_dbh = 0;
			opened = false;
		}
		
		struct adapter
		{
			callback cb;
			void* object;

			adapter(callback cb_in, void* object_in)
			: cb(cb_in)
			, object(object_in)
			{}
		};
	
		static int adapter_callback(void* obj, int colnr, char** values, char** names)
		{
			adapter* adp = (adapter*)obj;
			(*(adp->cb))(colnr, values, adp->object);
			return 0;
		}
	
		void runquery(const std::string& cmd, callback cb, void* object)
		{
			GENERIK_TRACER;
			GENERIK_TRACE_VALUE(cmd);
			char* errmsg = 0;
			int check = SQLITE_OK;
			try
			{
				mutex.lock();
				//GENERIK_TRACE_VALUE("dbh: "<<(void*)_dbh);
				if (cb)
				{
					//GENERIK_TRACE_VALUE("sqlite3_exec w. callbacks at :"<<(void*)&sqlite3_exec);
					adapter adp(cb, object);
					check = sqlite3_exec(_dbh, cmd.c_str(), adapter_callback, (void*)&adp, &errmsg);
				}
				else
				{
					//GENERIK_TRACE_VALUE("sqlite3_exec w/o callbacks at :"<<(void*)&sqlite3_exec);
					check = sqlite3_exec(_dbh, cmd.c_str(), 0, 0, &errmsg);
				}
				mutex.unlock();
				//GENERIK_TRACE_VALUE("finished run");
			}
			catch (...)
			{
				GENERIK_TRACE("caught an unknown exception?");
				check = !SQLITE_OK;
			}
			if (check != SQLITE_OK)
			{
				std::string error = "sqlite3_exec error: ";
				error += errmsg;
				error += " ["+cmd+"]";
				std::cerr<<error<<std::endl;
				sqlite3_free(errmsg);
			}
		}
		
		static void update_hook(void* object, int type, char const* database, char const* table, sqlite_int64 row)
		{
			//GENERIK_TRACER;
			((sqlite*)object)->_notifications.insert(table);
		}
		
		static void rollback_hook(void* object)
		{
			GENERIK_TRACER;
			generik::mutex& mutex = ((sqlite*)object)->mutex;
			THREAD_LOCK(mutex);
			((sqlite*)object)->_notifications.clear();
		}

		struct raiser
		{
			sqlite* db;
			std::string table;
		};
		static void* raise_notify(void* object)
		{
			GENERIK_TRACER;
			raiser* r = (raiser*)object;
			r->db->raise(r->table);
			delete r;
			return 0;
		}
		
		/** Creates a fire-and-forget thread for each notification.
		We need these in threads, because the notifiee will try and operate on the database
		when it receives this notification, and we have to hold a lock on the database
		in order to be able to deal with the notifications list.
		This will create a deadlock, since the notifiee will try and block on getting the mutex
		while this function is waiting for it to finish.
		*/
		static int commit_hook(void* object)
		{
			GENERIK_TRACER;
			((sqlite*)object)->mutex.lock();
			for (std::set<std::string>::iterator notification = ((sqlite*)object)->_notifications.begin(); notification != ((sqlite*)object)->_notifications.end(); ++notification)
			{
				GENERIK_TRACE_VALUE(*notification);
				raiser* r = new raiser;
				r->db = (sqlite*)object;
				r->table = *notification;
				pthread_t raisethread;
				pthread_create(&raisethread, 0, raise_notify, r);
				pthread_detach(raisethread); // not interested in result
			}
			// done with this list!
			((sqlite*)object)->_notifications.clear();
			((sqlite*)object)->mutex.unlock();
			return 0;
		}
		
		void listen(const std::string& table)
		{
			GENERIK_TRACER;
		}
		void unlisten(const std::string& table)
		{
			GENERIK_TRACER;
		}
		void notify(const std::string& table)
		{
			GENERIK_TRACER;
			raise(table);
		}
		
		std::string make_path(const std::string& path_in)
		{
			if (!path_in.empty())
			{
				if (path_in[0] != '/')
				{
					return generik::getcwd() + "/" + path_in;
				}
			}
			return path_in;
		}
		
		typedef void(*register_funcs_sig)(sqlite3*);
		void load_module(const std::string& path, const std::string& modulename)
		{
			GENERIK_TRACER;
			
			// if modulename is not an absolute path, prepend "./"
			std::string modulepathname = make_path(path + "/" + modulename);
			
			sqlite3_enable_load_extension(_dbh, true);
			//std::string result = generik::query(this, "select load_extension('" + path + "/" + modulename + "')");
			std::string result = generik::query(this, "select load_extension('" + modulepathname + "')");
			GENERIK_TRACE_VALUE(result);
		}
		
	};

}

#endif











